package cf.wfen.smsforward;

import java.util.HashMap;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsMonitor extends BroadcastReceiver {

    private final static boolean DEBUG = true;
	public static final String TAG = "SmsMonitor";

	public static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO: This method is called when the BroadcastReceiver is receiving
		// an Intent broadcast.
		// throw new UnsupportedOperationException("Not yet implemented");
		if(DEBUG)Log.i(TAG, "on receive," + intent.getAction());
		if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
			for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {

				String messageBody = smsMessage.getMessageBody();
				String address = smsMessage.getOriginatingAddress();

				HashMap<String, String[]> map = getSettings(context);
				for (String key : map.keySet()) {

					//关键词以 "-"开始 则检查短信内容是否有该关键字
					if (key.startsWith("-")) {
						String subcnt = key.substring(1);
						if (messageBody.indexOf(subcnt) > -1) {
							for (String addr : map.get(key)) {
								if(DEBUG)Log.i(TAG, "key " + key + " from " + address + " to " + addr + " msg " + messageBody);
								SmsManager.getDefault().sendTextMessage(addr, null, messageBody, null, null);
							}
							;
						}
					} else if(address.equals(key)) { //否则比较短信号码
						for (String addr : map.get(key)) {
							if(DEBUG)Log.i(TAG, "from " + address + " send " + addr + " content " + messageBody);
							SmsManager.getDefault().sendTextMessage(addr, null, messageBody, null, null);
						}
					}
				}
			}
		}
	}

	private HashMap<String, String[]> getSettings(Context context) {
		HashMap<String, String[]> map = new HashMap<String, String[]>();
		String settingsStr = context.getSharedPreferences("data", Context.MODE_PRIVATE).getString("settings", "");
		if(DEBUG)Log.i("settings", settingsStr);
		String[] lines = settingsStr.split("\n");
		int cnt = lines.length;
		for (int i = 0; i < cnt; i++) {
			String[] p1s = lines[i].split("\\|");
			String[] numbers = p1s[1].split("\\,");
			for (String num : numbers) {
				if(DEBUG)Log.i("num", num);
			}
			map.put(p1s[0], numbers);
		}
		return map;
	}
}